package com.von.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.von.enums.ApiErrorCode;
import com.von.result.R;
import com.von.util.RedisUtil;
import com.von.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author xiaosai
 * @version 1.0
 * @date 2021/6/21 15:24
 * @describe 拦截器配置
 * @className
 */
@Component
public class InterceptorConfig implements HandlerInterceptor {

    /**
     * 拦截器是在bean之前初始化，导致为null
     */
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StrUtil.isNotEmpty(token)&&token.contains(TokenUtils.TOKEN_PREFIX)){
            //TODO:拦截后应该执行的代码
            if(redisUtil.get(token)!=null){
                return true;
            }else {
                errorJson(response,R.failed(ApiErrorCode.LOGIN_TOKEN_LOSE));
                return false;
            }
        }else{
            return true;
        }
    }

    private void errorJson(HttpServletResponse response, R<String> r){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.append(JSON.toJSONString(r));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
